'use strict';

/**
 * Micro-Service Express.js "Error Handler" and "Error" creation methods for API responses
 */

function MsvcError(statusCode, message, data) {
  this.isMsvcError = true;
  this.statusCode = statusCode || 503;
  this.message = {
    message: message
  };
  this.data = data;
}

function create(statusCode, message, data) {
  var errorObj = new MsvcError(statusCode, message, data);
  return errorObj;
}

function relay(error, response, body) {
  var errorObj = new MsvcError();

  errorObj.error = error;
  errorObj.response = response;
  errorObj.originalBody = body;

  if (error) {
    errorObj.statusCode = 503;
  } else if (errorObj.response && errorObj.response.statusCode) {
    errorObj.statusCode = errorObj.response.statusCode;
  } else {
    errorObj.statusCode = 503;
  }

  // response might be null due to socket time out or other unexpected failure
  if (response && response.headers) {
    var contentType = response.headers['content-type'];
    // only add body if content type is some form of json
    if (contentType && contentType.indexOf('application/json') >= 0) {
      errorObj.message = Object.reject(body, ['stackTrace', 'description']);
    }
  }

  return errorObj;
}

function errorHandler() {
  return function (err, req, res, next) {
    if (err.isMsvcError) {
      res.status(err.statusCode).send(err.message);
    } else {
      next(err);
    }
  };
}

module.exports = {
  create: create,
  relay: relay,
  handler: errorHandler
};